


import 'package:flutter/material.dart';


//不断的保存到points，数量多了，就会卡
class SketchPad_1 extends StatefulWidget {
  const SketchPad_1({Key? key}) : super(key: key);

  @override
  State<SketchPad_1> createState() => _SketchPad_1State();
}

class _SketchPad_1State extends State<SketchPad_1> {
  final List<Offset?> points = [];
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onPanUpdate: (details){
          setState(() {
            points.add(details.localPosition);
          });
        },
        onPanEnd: (_){
          setState(() {
            points.add(null);
          });
        },
        child: CustomPaint(
          foregroundPainter: _SketchPainter(points),
          child: Container(color: Colors.yellow[100],),
        ));
  }
}

class _SketchPainter extends CustomPainter {
  List<Offset?> points;
  _SketchPainter(this.points);
  static final pen = Paint()
  ..color=Colors.black
  ..strokeWidth=2.0;
  @override
  void paint(Canvas canvas, Size size) {
    for(int i=0;i<points.length-1;i++){
      if(points[i]!=null && points[i+1]!=null){
        canvas.drawLine(points[i]!, points[i+1]!, pen);
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
